// 请求函数
import { baseUrl } from '@/utils/baseConfig.js'
import { tansParams } from '@/utils/tool.js'
import { encrypt, decrypt } from '@/utils/jsencrypt';
import { encryptBase64, encryptWithAes, generateAesKey, decryptWithAes, decryptBase64 } from '@/utils/crypto.js';


const encryptHeader = 'encrypt-key';

const request = (options) => {
	
	let type = 'application/json;charset=utf-8'
	if(options.method.toUpperCase() == 'GET' && options.params) {
		options.url = options.url + '?'+tansParams(options.params)
		options.params = {}
	}
	
	// 是否需要加密
	const isEncrypt = (options.headers || {}).isEncrypt === 'true';
	
	if (isEncrypt && (options.method.toUpperCase() === 'POST' || options.method.toUpperCase() === 'PUT')) {
	  // 生成一个 AES 密钥
	  const aesKey = generateAesKey();
	 
	  options.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
	  options.data = typeof options.data === 'object' ? encryptWithAes(JSON.stringify(options.data), aesKey) : encryptWithAes(options.data, aesKey);
	}
	
	return new Promise((resolve, reject)=>{
		uni.request({
			header: {
				"content-type": options.contentType||type,
				"Authorization": "Bearer " + uni.getStorageSync('token')|| "",
				"clientId": uni.getStorageSync('client_id')||"",
				// "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJzeXNfdXNlcjoxIiwicm5TdHIiOiJVcTM2bnoxTXF1M1JTMlBxUDAzZ3p5YUhrQjhMbEE0TyIsImNsaWVudGlkIjoiZTVjZDdlNDg5MWJmOTVkMWQxOTIwNmNlMjRhN2IzMmUiLCJ0ZW5hbnRJZCI6IjAwMDAwMCIsInVzZXJJZCI6MSwiZGVwdElkIjoxMDN9.SNb0Wkl1doW8cSp9STZ6Y5epb3t9-ydlrco8ButJUJk",
				// "client_id": "e5cd7e4891bf95d1d19206ce24a7b32e",
				...options.headers
			},
			timeout: 5000,
			url: baseUrl + options.url,
			method:options.method||"GET",
			data:options.data||{},
			success: (res)=>{
				let result = res.data
				// 加密后的 AES 秘钥
				const keyStr = res.headers&&res.headers[encryptHeader];
				// 加密
				if (keyStr != null && keyStr != '') {
				  const data = res.data;
				  // 请求体 AES 解密
				  const base64Str = decrypt(keyStr);
				  // base64 解码 得到请求头的 AES 秘钥
				  const aesKey = decryptBase64(base64Str.toString());
				  // aesKey 解码 data
				  const decryptData = decryptWithAes(data, aesKey);
				  // 将结果 (得到的是 JSON 字符串) 转为 JSON
				  result = JSON.parse(decryptData);
				}
				
				if(result.code === 401) {
					console.log("返回到指定页面")
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}
				
				resolve(result)
			},
			fail: err=>{
				reject(err)
			}
		})
	})
}

export default request